<template>
  <div>
    <el-form :inline="true" style="float:left;">
      <el-form-item>
        <el-input
            v-model="page.username"
            placeholder="用户名"
            clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getUserList">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="dialogVisible = true" v-if="hasPerm('sys:user:save')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="这是确定批量删除吗？" @confirm="delsHandle">
          <el-button type="danger" slot="reference" :disabled="delBtlStatus" v-if="hasPerm('sys:user:delete')">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange">

      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          label="头像"
          width="50">
        <template slot-scope="scope">
          <el-avatar size="small" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>

      <el-table-column
          prop="username"
          label="用户名"
          width="120">
      </el-table-column>
      <el-table-column
          prop="code"
          label="角色名称">
        <template slot-scope="scope">
          <el-tag size="small" type="info">{{scope.row.roleName}}</el-tag>
        </template>

      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱">
      </el-table-column>

      <el-table-column
          prop="status"
          label="状态">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.status === 1" type="success">正常</el-tag>
          <el-tag size="small" v-else-if="scope.row.status === 0" type="danger">禁用</el-tag>
        </template>

      </el-table-column>
      <el-table-column
          prop="createTime"
          width="200"
          label="创建时间"
      >
      </el-table-column>
      <el-table-column
          prop="icon"
          width="260px"
          label="操作">

        <template slot-scope="scope">
          <el-button type="text" @click="roleHandle(scope.row.id)" v-if="hasPerm('sys:user:update')">分配角色</el-button>
          <el-divider direction="vertical"></el-divider>

          <el-button type="text" @click="repassHandle(scope.row.id, scope.row.username)" v-if="hasPerm('sys:user:update')">重置密码</el-button>
          <el-divider direction="vertical"></el-divider>

          <el-button type="text" @click="editHandle(scope.row)" v-if="hasPerm('sys:user:update')">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(scope.row.id)">
              <el-button type="text" slot="reference" v-if="hasPerm('sys:user:delete')">删除</el-button>
            </el-popconfirm>
          </template>

        </template>
      </el-table-column>

    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="page.current"
        :page-size="page.size"
        :total="page.total">
    </el-pagination>


    <!--新增对话框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose">

      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="editForm.username" autocomplete="off"></el-input>
          <el-alert
              title="初始密码为888888"
              :closable="false"
              type="info"
              style="line-height: 12px;"
          ></el-alert>
        </el-form-item>

        <el-form-item label="邮箱"  prop="email" label-width="100px">
          <el-input v-model="editForm.email" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="状态"  prop="status" label-width="100px">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm()">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogFormVisible" width="600px">

      <el-select v-model="roleId" placeholder="请选择">
        <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <div slot="footer" class="dialog-footer">
        <el-button @click="roleDialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitRoleHandle()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Role",
  data() {
    return {
      page:{
        total: 0,
        size: 10,
        current: 1,
        username:'',
      },
      delBtlStatus: true,
      dialogVisible: false,
      editForm: {
      },
      tableData: [],
      editFormRules: {
        username: [
          {required: true, message: '请输入用户名称', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ]
      },
      multipleSelection: [],
      roleDialogFormVisible: false,
      roleId:'',
      roleList:[],
      userId:''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.delBtlStatus = val.length == 0
    },
    handleSizeChange(val) {
      this.page.size = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.getUserList()
    },
    resetForm() {
      this.$refs["editForm"].resetFields();
      this.dialogVisible = false
      this.editForm = {}
    },
    handleClose() {
      this.resetForm('editForm')
    },
    getUserList() {
      this.$axios.get("/api/sys/user/getAllUser/"+this.page.current+"/"+this.page.size+(this.page.username?'?username='+this.page.username:'')).then(res => {
        this.page.current=res.data.data.current
        this.page.total=res.data.data.total
        this.tableData = res.data.data.records
      })
    },
    submitForm() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.$axios.post('/api/sys/user/' + (this.editForm.id?'updateUser':'saveUser/1'), this.editForm)
              .then(res => {
                this.$message({
                  showClose: true,
                  message: res.data.msg?res.data.msg:'操作成功',
                  type: 'success',
                  onClose:() => {
                    this.getUserList()
                  }
                });
                this.dialogVisible = false
              })
        } else {
          return false;
        }
      });
    },
    editHandle(user) {
      this.editForm=user
        this.dialogVisible = true
    },

    //批量删除
    delsHandle(){
      this.$axios.post('/api/sys/user/deleteUsers',this.multipleSelection).then(res=>{
        this.$message.success(res.data.msg)
      }).finally(()=>{
        this.getUserList()
      })
    },
    delHandle(id) {

      this.$axios.delete("/api/sys/user/deleteUser/"+id).then(res => {
        this.$message({
          showClose: true,
          message: res.data.msg?res.data.msg:'操作成功',
          type: 'success',
          onClose:() => {
            this.getUserList()
          }
        });
      })
    },
    roleHandle (id) {
      this.$axios.get("/api/sys/role/getRoleList").then(res=>{
        this.roleList=res.data.data
      })

     //获取当前用户的角色id
      this.$axios.get('/api/sys/user/getUserRole/'+id).then(res=>{
        this.roleId=res.data.data.id
      })
      this.userId=id
      this.roleDialogFormVisible = true
    },
    submitRoleHandle() {
      this.$axios.post('/api/sys/user/updateRole/' + this.userId+'/'+this.roleId).then(res => {
        this.$message({
          showClose: true,
          message: res.data.msg?res.data.msg:'操作成功',
          type: 'success',
          onClose:() => {
            this.getUserList()
          }
        });
        this.roleDialogFormVisible = false
      })
    },
    repassHandle(id, username) {
      this.$confirm('将重置用户【' + username + '】的密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post("/api/sys/user/replacePass/"+id).then(res => {
          this.$message({
            showClose: true,
            message: res.data.msg?res.data.msg:'操作成功',
            type: 'success',
            onClose: () => {
            }
          });
        })
      })
    }
  }
}
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>